//
//  HJDResigerRecordViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/6/20.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDResigerRecordViewController.h"
#import "HJDResigrRecordTableViewCell.h"
#import "HJDResigrRecordTableViewCell.h"

#import "AFNetworking.h"
#import "HJDRegistrationModel.h"

#import "MJExtension.h"
#import "MJRefresh.h"


@interface HJDResigerRecordViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    int pageS;
    int pages;
    int n;
    
}


@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * statuses;

@property (nonatomic,strong) NSString * pageCount;







@end

@implementation HJDResigerRecordViewController

-(NSMutableArray *)statuses
{
    if (_statuses ==nil) {
        
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor getColorWithHexNumber:@"F1F0EE"];
    self.title = @"挂号记录";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(popToPre) image:@"︿" HighImage:nil];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, HJDWidth, HJDHeight)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
   
    NSUserDefaults *idDe = [NSUserDefaults standardUserDefaults];
    NSString *ID = [idDe objectForKey:@"Id"];
    
    self.pageCount = @"1";
//    NSString *path = @"http://gh.120hfz.com:8091/app_czlist.php";
    NSString *url = @"/app/queryRegistrationLog.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"pageSize"]= self.pageCount;
    params[@"userId"]= ID;
    
    [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//         NSLog(@"res%@",responseObject);
        NSDictionary *info =(NSDictionary *)responseObject;
        NSMutableArray *arrayR = info[@"resultMap"][@"record"];
        NSString *sum = info[@"resultMap"][@"sum"][@"count"];
//        NSLog(@"sum=%@",sum);
      

        NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
        [defaS setObject:sum forKey:@"countSum"];
        
        self.statuses = (NSMutableArray *)[HJDRegistrationModel mj_objectArrayWithKeyValuesArray:arrayR];
     
        [self.tableView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"服务器升级，请稍后再试"];
    }];

    
    //添加下拉刷新控件
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
//    添加上拉加载更多
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadOldStatus)];
    

    NSUserDefaults *defa = [NSUserDefaults standardUserDefaults];
    NSString *page = [defa objectForKey:@"countSum"];
    pageS = [page intValue];
    

//   总页数
    pages = (pageS/10) +1 ;
//    NSLog(@"pageS=%dpages=%d",pageS,pages);
    n = 1;
   }


-(void)popToPre
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)loadNewStatus{

    
    if (n <1) {
        
    
    
    self.pageCount = [NSString stringWithFormat:@"%d",n];

    NSUserDefaults *idDe = [NSUserDefaults standardUserDefaults];
    NSString *ID = [idDe objectForKey:@"Id"];
//    NSString *path = @"http://gh.120hfz.com:8091/app_czlist.php";
    NSString *url = @"/app/queryRegistrationLog.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"pageSize"]= self.pageCount;
        params[@"userId"]= ID;
    [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
         [self.tableView.mj_header endRefreshing];
        
        NSDictionary *info =(NSDictionary *)responseObject;
        NSMutableArray *arrayR = info[@"resultMap"][@"record"];
       
        
        NSArray *statuses = (NSMutableArray *)[HJDRegistrationModel mj_objectArrayWithKeyValuesArray:arrayR];
        //防止覆盖后面的数据
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
        //刷新最新的数据，插入到最前面，防止覆盖后面的数据
        [self.statuses insertObjects:statuses atIndexes:indexSet];

        [self.tableView reloadData];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"服务器升级，请稍后再试"];
       
    }];
    
    }else{
        
        [self.tableView.mj_header endRefreshing];
    }
}

-(void)loadOldStatus
{
    NSUserDefaults *defaS = [NSUserDefaults standardUserDefaults];
    NSString *page = [defaS objectForKey:@"countSum"];
    pageS = [page intValue];
//    NSLog(@"pag= %d",pageS);

    
    if (pageS%10 != 0) {
        n += 1;
       
    }else{
        n+= 1;
    }
    if (n <= pages) {
        
    
    
    self.pageCount = [NSString stringWithFormat:@"%d",n];
    
    NSUserDefaults *idDe = [NSUserDefaults standardUserDefaults];
    NSString *ID = [idDe objectForKey:@"Id"];
//    NSString *path = @"http://gh.120hfz.com:8091/app_czlist.php";
    NSString *url = @"/app/queryRegistrationLog.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
        //    NSUserDefaults *phonede = [NSUserDefaults standardUserDefaults];
        //    NSString *phone = [phonede objectForKey:@"phonenum"];
       

        params[@"pageSize"]= self.pageCount;
        //    params[@"phone"]= phone;
        params[@"userId"]= ID;
    [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        [self.tableView.mj_footer endRefreshing];
        
        NSDictionary *info =(NSDictionary *)responseObject;
        NSMutableArray *arrayR = info[@"resultMap"][@"record"];
      NSArray *arr= (NSMutableArray *)[HJDRegistrationModel mj_objectArrayWithKeyValuesArray:arrayR];
        
        [self.statuses addObjectsFromArray:arr];
      
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD showError:@"服务器升级，请稍后再试"];

    }];
    }else{
        
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD showError:@"最后一页了"];
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statuses.count;
    
  }

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *identifier = @"RCell";

    HJDResigrRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier ];

    if (cell == nil) {
        cell = [[HJDResigrRecordTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    
    HJDRegistrationModel *reg = self.statuses[indexPath.row];
 
    
//    NSTimeInterval time = [reg.order_date doubleValue];
//    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
//    NSLog(@"date%@",date);
    
    cell.desk.text = @"妇产科 门诊";
    cell.hosName.text = @"常州武进红房子医院";
    if (reg.flag == 0) {
        cell.state.text = @"未到诊";
    }else if (reg.flag ==1){
        cell.state.text = @"已到诊";
    }else if (reg.flag == 2){
        cell.state.text = @"已失效";
    }

    
//    if (reg.status == 0) {
//    cell.state.text = @"未到诊";
//    }else if (reg.status ==1){
//    cell.state.text = @"已到诊";
//    }
    
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
//    NSDateComponents *comp = [[NSDateComponents alloc]init];
//    NSInteger flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
//    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    
//    comp = [calendar components:flags fromDate:date];
//    NSInteger month = [comp month];
//    NSInteger day = [comp day];
//    NSInteger year = [comp year];
//    
//    cell.day.text = [NSString stringWithFormat:@"/%ld",(long)day];
//
//    cell.month.text = [NSString stringWithFormat:@"%ld",(long)month];
//    cell.year.text = [NSString stringWithFormat:@"%ld",(long)year];
//
    NSString *str = @"/";
    cell.day.text = [str stringByAppendingString:[reg.subscribeTime substringWithRange:NSMakeRange(8, 2)]];
    
    cell.month.text = [reg.subscribeTime substringWithRange:NSMakeRange(5, 2)];
    cell.year.text = [reg.subscribeTime substringWithRange:NSMakeRange(0, 4)];
    

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;


    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 102;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HJDResigrRecordTableViewCell *Rcell = [tableView cellForRowAtIndexPath:indexPath ];
    Rcell.shuView.backgroundColor = [UIColor getColorWithHexNumber:@"D6D6D6"];
    
}
@end
